package org.misalen.web.admin.controllers;

import java.math.BigDecimal;

import org.misalen.web.admin.util.RedPacket;
import org.misalen.web.admin.util.ServerResult;
import org.misalen.web.database.model.mysql.pro.ProMapAdvertising;
import org.misalen.web.database.util.PaginationFrom;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/pro-map-advertising")
public class ProMapAdvertisingController extends BaseController {

	/**
	 * 列表页
	 * 
	 * @return 列表目标页
	 */
	@RequestMapping(value = "/", method = { RequestMethod.GET })
	public ModelAndView list() {
		ModelAndView modelAndView = new ModelAndView("/proMapAdvertising/list");
		return modelAndView;
	}

	/**
	 * 列表
	 * 
	 * @param 搜索条件
	 * @param 分页/排序条件
	 * @return 查询结果
	 */
	@RequestMapping(value = "/", method = { RequestMethod.POST })
	public @ResponseBody ServerResult listPost(ProMapAdvertising proMapAdvertising,
			PaginationFrom<ProMapAdvertising> pagination) {
		PaginationFrom<ProMapAdvertising> from = proMapAdvertisingRepository.findPageByBean(proMapAdvertising,
				pagination);
		return renderSuccess(from);
	}

	@RequestMapping(value = "/underReview/", method = { RequestMethod.GET })
	public ModelAndView underReview() {
		ModelAndView modelAndView = new ModelAndView("/proMapAdvertising/underReview");
		return modelAndView;
	}

	@RequestMapping(value = "/underReview/pass/{primaryKey}", method = { RequestMethod.GET })
	public @ResponseBody ServerResult underReviewPost(@PathVariable String primaryKey) {
		ProMapAdvertising proVideoInfo = proMapAdvertisingRepository.get(ProMapAdvertising.class, primaryKey);
		if (proVideoInfo.getState().equals("underReview")) {
			int total=new BigDecimal(proVideoInfo.getPromotionExpenses()).multiply(new BigDecimal(0.3f)).intValue();
			int total2=new BigDecimal(proVideoInfo.getPromotionExpenses()).subtract(new BigDecimal(total)).intValue();
			
			int[] is = RedPacket.generate(total, proVideoInfo.getPromotionNumber(), 10,
					total);
			int[] is2 = RedPacket.generate(total2, proVideoInfo.getPromotionNumber(), 50,
					total2);
			if (is != null&&is2 != null) {
				proVideoInfo.setState("generalize");
				proMapAdvertisingRepository.update(proVideoInfo);
				proMapRewardRepository.saveList(is,is2, proVideoInfo.getPrimaryKey());
			} else {
				return ServerResult.error("红包不能分配");
			}
		}
		return ServerResult.ok();
	}
}
